//
//  CLRMEffectTypeView.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/8/4.
//

#import "CLRMEffectTypeView.h"
#import "CLReadMenu.h"
@interface CLRMEffectTypeView ()
@property (nonatomic, strong) NSArray *effectNames;

@property (nonatomic, strong) NSMutableArray <UIButton *>*items;

@property (nonatomic, strong) UIButton *selectItem;
@end
@implementation CLRMEffectTypeView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _effectNames = @[@"仿真",@"覆盖",@"平移",@"滚动",@"无效果"];
    }
    return self;
}

- (void)addSubviews {
    [super addSubviews];
    self.backgroundColor = UIColor.clearColor;
    
    for (NSString *effectName in _effectNames) {
        NSUInteger i = [_effectNames indexOfObject:effectName];
        UIButton *item = [UIButton buttonWithType:UIButtonTypeCustom];
        item.tag = i;
        item.layer.cornerRadius = CL_SPACE_SA_6;
        item.layer.borderColor = CL_READ_COLOR_MENU_COLOR.CGColor;
        item.layer.borderWidth = CL_SPACE_SA_1;
        item.titleLabel.font = CL_FONT_SA_12;
        [item setTitle:effectName forState:(UIControlStateNormal)];
        [item setTitleColor:CL_READ_COLOR_MENU_COLOR forState:UIControlStateNormal];
        [item setTitleColor:CL_READ_COLOR_MAIN forState:UIControlStateSelected];
        [item addTarget:self action:@selector(clickItem:) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self addSubview:item];
        [self.items addObject:item];
        if (i == [CLReadConfigure sharedInstance].effectIndex) {
            [self selectItem:item];
        }
    }
}

- (void)selectItem:(UIButton *)item {
    
    self.selectItem.selected = NO;
    
    _selectItem.layer.borderColor = CL_READ_COLOR_MENU_COLOR.CGColor;
    
    item.selected = YES;
    
    item.layer.borderColor =  CL_READ_COLOR_MAIN.CGColor;
    
    _selectItem = item;
}

- (void)clickItem:(UIButton *)item {
    
    if ([_selectItem isEqual:item]) {
        return;
    }
    
    [self selectItem:item];
    
    [CLReadConfigure sharedInstance].fontIndex = item.tag;
    
    [[CLReadConfigure sharedInstance] save];
    
    [self.readMenu.delegate readMenuClickEffect:self.readMenu];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    NSUInteger count = _effectNames.count;
    
    CGFloat w = self.frame.size.width;
    CGFloat h = self.frame.size.height;
    
    CGFloat itemW = CL_SPACE_SA_60;
    CGFloat itemH = CL_SPACE_SA_30;
    CGFloat itemY = (h - itemH) / 2;
    CGFloat itemSpaceW = (w - (CGFloat)count * itemW) / (CGFloat)(count - 1);
    
    for (UIButton *item in _items) {
        item.frame = CGRectMake((CGFloat)[_items indexOfObject:item] * (itemW + itemSpaceW), itemY, itemW, itemH);
    }
}

@end
